'use strict';
const db = uniCloud.database();
const crypto = require('crypto');

// 密码加密函数
function encryptPassword(password) {
	return crypto.createHash('sha256').update(password).digest('hex');
}

// 生成JWT Token
function generateToken(userId, username, role) {
	const payload = {
		userId,
		username,
		role,
		iat: Date.now(),
		exp: Date.now() + 7 * 24 * 60 * 60 * 1000 // 7天过期
	};
	return Buffer.from(JSON.stringify(payload)).toString('base64');
}

exports.main = async (event, context) => {
	const { username, password, role } = event;
	
	// 参数验证
	if (!username || !password || !role) {
		return {
			code: 400,
			message: '用户名、密码和角色不能为空'
		};
	}
	
	// 验证角色类型
	if (!['user', 'admin'].includes(role)) {
		return {
			code: 400,
			message: '无效的角色类型'
		};
	}
	
	try {
		// 加密密码
		const encryptedPassword = encryptPassword(password);
		
		// 查询用户
		const userCollection = db.collection('user');
		const userQuery = await userCollection
			.where({
				username: username,
				password: encryptedPassword,
				role: role
			})
			.get();
		
		if (userQuery.data.length === 0) {
			return {
				code: 401,
				message: '用户名、密码或角色错误'
			};
		}
		
		const user = userQuery.data[0];
		
		// 检查用户状态
		if (user.status === 'disabled') {
			return {
				code: 403,
				message: '账户已被禁用'
			};
		}
		
		// 生成token
		const token = generateToken(user._id, user.username, user.role);
		
		// 更新最后登录时间
		await userCollection.doc(user._id).update({
			last_login_date: Date.now(),
			last_login_ip: context.CLIENTIP
		});
		
		// 返回登录成功信息
		return {
			code: 0,
			message: '登录成功',
			data: {
				token: token,
				userInfo: {
					userId: user._id,
					username: user.username,
					role: user.role,
					nickname: user.nickname || user.username,
					avatar: user.avatar || '',
					email: user.email || '',
					phone: user.mobile || ''
				}
			}
		};
		
	} catch (error) {
		console.error('登录错误:', error);
		return {
			code: 500,
			message: '服务器内部错误'
		};
	}
};